package cn.fufeiii.bt.common.util;

import cn.hutool.core.date.DatePattern;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.databind.json.JsonMapper;
import com.fasterxml.jackson.databind.module.SimpleModule;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import com.fasterxml.jackson.datatype.jsr310.deser.LocalDateTimeDeserializer;
import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateTimeSerializer;
import com.fasterxml.jackson.module.paramnames.ParameterNamesModule;

import java.text.SimpleDateFormat;
import java.time.LocalDateTime;

/**
 * jackson工具类
 * 配置的参数可以参考{@link org.springframework.http.converter.json.Jackson2ObjectMapperBuilder#build()}
 *
 * @author FuFei
 */
public final class JsonUtil {

    private final static JsonMapper JSON_MAPPER = new JsonMapper();

    static {
        // 序列化/反序列化 设置Date的日期格式
        JSON_MAPPER.setDateFormat(new SimpleDateFormat(DatePattern.NORM_DATETIME_PATTERN));

        // 关闭Date转时间戳
        JSON_MAPPER.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);

        // 忽略空bean转json的错误
        JSON_MAPPER.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);

        // 枚举的序列化和反序列化使用 toString()
        JSON_MAPPER.configure(SerializationFeature.WRITE_ENUMS_USING_TO_STRING, true);
        JSON_MAPPER.configure(DeserializationFeature.READ_ENUMS_USING_TO_STRING, true);

        // 忽略未知的json字段转bean
        JSON_MAPPER.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);

        // 注册基础模块
        JSON_MAPPER.registerModules(new JavaTimeModule(), new ParameterNamesModule());

        // 在额外兼容LocalDateTime的日期格式
        SimpleModule module = new SimpleModule();
        module.addDeserializer(LocalDateTime.class, new LocalDateTimeDeserializer(DatePattern.NORM_DATETIME_FORMATTER));
        module.addSerializer(LocalDateTime.class, new LocalDateTimeSerializer(DatePattern.NORM_DATETIME_FORMATTER));
        JSON_MAPPER.registerModules(module);
    }


    public static JsonMapper newMapper() {
        return JSON_MAPPER.copy();
    }

    public static String toJson(Object o) {
        try {
            return JSON_MAPPER.writeValueAsString(o);
        } catch (JsonProcessingException e) {
            throw new RuntimeException(e);
        }
    }

    public static <T> T toObject(String json, Class<T> clazz) {
        try {
            return JSON_MAPPER.readValue(json, clazz);
        } catch (JsonProcessingException e) {
            throw new RuntimeException(e);
        }
    }

    public static <T> T toObject(String json, TypeReference<T> typeReference) {
        try {
            return JSON_MAPPER.readValue(json, typeReference);
        } catch (JsonProcessingException e) {
            throw new RuntimeException(e);
        }
    }

}
